package com.tensquare.user.service;

import cn.hutool.crypto.SecureUtil;
import com.tensquare.entity.IdWorker;
import com.tensquare.user.dao.UserDao;
import com.tensquare.user.pojo.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author zzb
 * @create 2021/2/22
 */
@Service
public class UserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private UserDao userDao;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    //通过rabbitmq发送相关消息
    public void sendMessage(String mobile) {
        //生成6位数验证码
        int min = 100000;   //6位数最小值
        int max = 999999;   //6位数最大值
        Random random = new Random();
        int code = random.nextInt(max - min);//得到一个【0，max-min）的随机数
        if (code < min){
            code += min;
        }
        System.out.println("code = " + code);
        //将验证码放到redis中
        redisTemplate.opsForValue().set(mobile,code,10, TimeUnit.HOURS);
        //发送消息
        Map<String,String> map = new HashMap<>();
        map.put("mobile",mobile);   //手机号
        map.put("code",code+"");    //验证码
        //发送消息
        rabbitTemplate.convertAndSend("sms",map);
    }

    //用户注册
    public Boolean add(User user, String code) {
        //验证验证码是否正确
        //从redis中取得验证码进行比对
        String vildcode = (String) redisTemplate.opsForValue().get("code");
        if (!code.equals(code)){//与用户传进来的验证码进行比较
            return false;
        }
        user.setId(idWorker.nextId()+"");
        user.setFollowcount(0);   //关注数
        user.setFanscount(0);       //关注数
        user.setOnline(0L);           //在线时长
        user.setRegdate(new Date());//注册日期
        user.setUpdatedate(new Date());//更新日期
        user.setLastdate(new Date());//最后登录日期
        //user.setPassword(SecureUtil.md5(user.getPassword()));//md5加密
        //将密码进行Bcrptpassword加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //添加用户
        userDao.save(user);
        return true;
    }

    //用户登录
    public User findUser(User user) {
        //根据手机号查询用户
        User loginUser = userDao.findByMobile(user.getMobile());
        //判断是否存在，如果存在，就验证密码
        if (loginUser != null && passwordEncoder.matches(user.getPassword(),loginUser.getPassword())){
            return loginUser;
        }
        return null;
    }

    //根据id删除用户
    public void deleteById(String userId) {
        userDao.deleteById(userId);
    }
}
